package com.example.controller;

import com.example.service.BalanceService;
import com.example.entity.Balance;
import com.example.entity.BalanceToken;
import com.example.mapper.BalanceMapper;
import com.example.mapper.BalanceTokenMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.example.common.ApiResult;
import jakarta.annotation.Resource;
import java.util.List;

/**
 * 钱包余额同步相关接口，供xxl-job等定时任务调用
 */
@RestController
@RequestMapping("/api/balance")
@Tag(name = "余额管理", description = "ETH/Token余额同步相关接口")
public class BalanceController {

    @Resource
    private BalanceService balanceService;
    @Resource
    private BalanceMapper balanceMapper;
    @Resource
    private BalanceTokenMapper balanceTokenMapper;

    /**
     * 遍历所有钱包地址，批量同步ETH和Token余额
     * 可由xxl-job定时调用
     */
    @PostMapping("/sync-all")
    @Operation(summary = "批量同步所有钱包ETH和Token余额", description = "遍历tb_balance和tb_balance_token表，调用余额同步方法，供xxl-job等定时任务触发。")
    public ApiResult<String> syncAllBalances() {
        // 查询所有ETH钱包地址
        List<Balance> ethList = balanceMapper.selectList(null);
        for (Balance b : ethList) {
            balanceService.syncEthBalance(b.getWalletAddress(), b.getEthBalance());
        }
        // 查询所有Token钱包+合约地址
        List<BalanceToken> tokenList = balanceTokenMapper.selectList(null);
        for (BalanceToken t : tokenList) {
            balanceService.syncTokenBalance(t.getWalletAddress(), t.getTokenAddress(), t.getTokenBalance());
        }
        return ApiResult.success("同步钱包余额任务已触发", null);
    }
}
